package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
        System.out.println("进入自媒体平台登录页面");
       //TODO
        HashMap map = new HashMap<>();
        //判断传递的用户和密码是否为空
        if (StringUtils.isNotBlank(dto.getName()) && StringUtils.isNotBlank(dto.getPassword())){
            //获取数据库中数据表
            WmUser wmUser = this.lambdaQuery().eq(WmUser::getName, dto.getName()).one();
            //用户不存在
            if (wmUser ==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            //加密
            String salt = BCrypt.gensalt();
            String hashpw = BCrypt.hashpw(dto.getPassword(), salt);
            //密码错误
            boolean result = BCrypt.checkpw(dto.getPassword(),hashpw);
            if (!result){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //状态码
            Integer status = wmUser.getStatus();
            if (status!=9){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
            }
            //正常登录
            String token = AppJwtUtil.getToken(wmUser.getId().longValue());
            map.put("token",token);
            map.put("user",wmUser);
            return ResponseResult.okResult(map);
        }
        return null;
    }
}